 ///
 /// @file    Point.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2016-03-11 14:35:06
 ///
 
#include <iostream>
#include <memory>

using std::cout;
using std::endl;

class Point : public std::enable_shared_from_this<Point>
{
public:
	Point(int ix = 0, int iy = 0)
	: _ix(ix)
	, _iy(iy)
	{
		cout << "Point(int, int)" << endl;
	}

	Point(const Point & rhs)
	: _ix(rhs._ix)
	, _iy(rhs._iy)
	{
		cout << "Point(const Point & rhs)" << endl;
	}

	std::shared_ptr<Point> add(const Point * rhs)
	{//如果是直接返回裸指针，会脱离shared_ptr的控制
	 //也会造成两次析构的问题,所以它的返回值应该是
	 //shared_ptr
		_ix += rhs->_ix;
		_iy += rhs->_iy;
		//return std::shared_ptr<Point>(this);
		return shared_from_this();//在类内部通过this指针返回shared_ptr对象
	}

	~Point()
	{
		cout << "~Point()" << endl;
	}
private:
	int _ix;
	int _iy;
};

Point func()
{
	Point tmp(1, 2);
	return tmp;
}

int test0(void)
{
	Point * pt = new Point(1, 2);//该对象会被析构两次
	std::shared_ptr<Point> spt1(pt);//不要把原生的裸指针交给不同的shared_ptr进行托管
	//std::shared_ptr<Point> pt2(pt);
	//std::shared_ptr<Point> spt2(spt1);

	std::shared_ptr<Point> spt3(new Point(3, 4));
	spt3.reset(spt1.get());//对于reset函数的误用
	return 0;
}

int main(void)
{
	Point * pt = new Point(1, 2);
	std::shared_ptr<Point> spt1(pt);
	std::shared_ptr<Point> spt2(new Point(3, 4));
	//std::shared_ptr<Point> spt3(spt2->add(spt1.get()));
	spt2->add(spt1.get());

	return 0;
}
